// API接口定义
import Request from '@/utils/request'
import type { ApiResponse, PaginationParams, PaginationResult } from '@/types'

// 用户相关接口
export interface LoginParams {
  username: string
  password: string
  captcha?: string
  remember?: boolean
}

export interface RegisterParams {
  username: string
  email: string
  password: string
  confirmPassword: string
  phone?: string
  captcha: string
  agreement: boolean
}

export interface UserInfo {
  id: string
  username: string
  email: string
  phone?: string
  avatar?: string
  nickname?: string
  role: string
  permissions: string[]
  lastLoginTime?: string
  createdAt: string
  updatedAt: string
}

export interface UpdateProfileParams {
  nickname?: string
  email?: string
  phone?: string
  avatar?: string
}

export interface ChangePasswordParams {
  oldPassword: string
  newPassword: string
  confirmPassword: string
}

// 产品相关接口
export interface Product {
  id: string
  name: string
  description: string
  shortDescription: string
  price: number
  originalPrice?: number
  images: string[]
  category: string
  tags: string[]
  features: string[]
  specifications: Record<string, any>
  status: 'active' | 'inactive' | 'draft'
  stock: number
  sales: number
  rating: number
  reviewCount: number
  createdAt: string
  updatedAt: string
}

export interface ProductCategory {
  id: string
  name: string
  description?: string
  icon?: string
  parentId?: string
  children?: ProductCategory[]
  productCount: number
  sort: number
  status: 'active' | 'inactive'
}

export interface ProductFilter {
  category?: string
  priceRange?: [number, number]
  tags?: string[]
  rating?: number
  inStock?: boolean
  search?: string
}

export interface ProductSort {
  field: 'price' | 'sales' | 'rating' | 'createdAt'
  order: 'asc' | 'desc'
}

// 解决方案相关接口
export interface Solution {
  id: string
  title: string
  description: string
  content: string
  summary: string
  industry: string
  tags: string[]
  features: string[]
  benefits: string[]
  technologies: string[]
  caseStudies: CaseStudy[]
  images: string[]
  documents: Document[]
  status: 'published' | 'draft' | 'archived'
  viewCount: number
  createdAt: string
  updatedAt: string
}

export interface CaseStudy {
  id: string
  title: string
  description: string
  client: string
  industry: string
  challenge: string
  solution: string
  results: string[]
  images: string[]
  testimonial?: {
    content: string
    author: string
    position: string
    company: string
    avatar?: string
  }
  createdAt: string
}

// 新闻资讯相关接口
export interface News {
  id: string
  title: string
  content: string
  summary: string
  author: string
  category: string
  tags: string[]
  coverImage?: string
  images: string[]
  status: 'published' | 'draft' | 'archived'
  featured: boolean
  viewCount: number
  likeCount: number
  commentCount: number
  publishedAt: string
  createdAt: string
  updatedAt: string
}

export interface NewsCategory {
  id: string
  name: string
  description?: string
  newsCount: number
  sort: number
}

// 联系表单相关接口
export interface ContactForm {
  name: string
  company?: string
  phone: string
  email: string
  consultationType: string
  budget?: string
  requirements: string
  attachments?: File[]
}

export interface ContactRecord {
  id: string
  name: string
  company?: string
  phone: string
  email: string
  consultationType: string
  budget?: string
  requirements: string
  attachments: string[]
  status: 'pending' | 'processing' | 'completed' | 'closed'
  assignedTo?: string
  notes?: string
  createdAt: string
  updatedAt: string
}

// 文件上传相关接口
export interface UploadResponse {
  url: string
  filename: string
  size: number
  type: string
}

// 统计数据相关接口
export interface Statistics {
  totalUsers: number
  totalProducts: number
  totalSolutions: number
  totalNews: number
  monthlyVisits: number
  monthlyRegistrations: number
  conversionRate: number
  customerSatisfaction: number
}

// API类
class API {
  // 用户相关API
  static user = {
    /**
     * 用户登录
     */
    login(params: LoginParams) {
      return Request.post<{ token: string; refreshToken: string; user: UserInfo }>(
        '/auth/login',
        params,
        { showSuccess: true, successMessage: '登录成功' }
      )
    },
    
    /**
     * 用户注册
     */
    register(params: RegisterParams) {
      return Request.post<{ user: UserInfo }>(
        '/auth/register',
        params,
        { showSuccess: true, successMessage: '注册成功' }
      )
    },
    
    /**
     * 用户登出
     */
    logout() {
      return Request.post('/auth/logout')
    },
    
    /**
     * 刷新Token
     */
    refreshToken(refreshToken: string) {
      return Request.post<{ token: string; refreshToken: string }>(
        '/auth/refresh',
        { refreshToken }
      )
    },
    
    /**
     * 获取用户信息
     */
    getUserInfo() {
      return Request.get<UserInfo>('/user/profile')
    },
    
    /**
     * 更新用户信息
     */
    updateProfile(params: UpdateProfileParams) {
      return Request.put<UserInfo>(
        '/user/profile',
        params,
        { showSuccess: true, successMessage: '更新成功' }
      )
    },
    
    /**
     * 修改密码
     */
    changePassword(params: ChangePasswordParams) {
      return Request.put(
        '/user/password',
        params,
        { showSuccess: true, successMessage: '密码修改成功' }
      )
    },
    
    /**
     * 上传头像
     */
    uploadAvatar(file: File) {
      return Request.upload<UploadResponse>('/user/avatar', file)
    }
  }
  
  // 产品相关API
  static product = {
    /**
     * 获取产品列表
     */
    getProducts(params: PaginationParams & ProductFilter & { sort?: ProductSort }) {
      return Request.get<PaginationResult<Product>>('/products', params)
    },
    
    /**
     * 获取产品详情
     */
    getProduct(id: string) {
      return Request.get<Product>(`/products/${id}`)
    },
    
    /**
     * 获取产品分类
     */
    getCategories() {
      return Request.getCached<ProductCategory[]>('/products/categories', undefined, {
        cache: true,
        cacheTTL: 10 * 60 * 1000 // 10分钟缓存
      })
    },
    
    /**
     * 搜索产品
     */
    searchProducts(keyword: string, params?: PaginationParams) {
      return Request.get<PaginationResult<Product>>('/products/search', {
        keyword,
        ...params
      })
    },
    
    /**
     * 获取热门产品
     */
    getPopularProducts(limit = 10) {
      return Request.getCached<Product[]>('/products/popular', { limit }, {
        cache: true,
        cacheTTL: 5 * 60 * 1000 // 5分钟缓存
      })
    },
    
    /**
     * 获取推荐产品
     */
    getRecommendedProducts(productId?: string, limit = 10) {
      return Request.get<Product[]>('/products/recommended', {
        productId,
        limit
      })
    }
  }
  
  // 解决方案相关API
  static solution = {
    /**
     * 获取解决方案列表
     */
    getSolutions(params: PaginationParams & { industry?: string; search?: string }) {
      return Request.get<PaginationResult<Solution>>('/solutions', params)
    },
    
    /**
     * 获取解决方案详情
     */
    getSolution(id: string) {
      return Request.get<Solution>(`/solutions/${id}`)
    },
    
    /**
     * 获取案例研究
     */
    getCaseStudies(params: PaginationParams & { industry?: string; solutionId?: string }) {
      return Request.get<PaginationResult<CaseStudy>>('/case-studies', params)
    },
    
    /**
     * 获取案例详情
     */
    getCaseStudy(id: string) {
      return Request.get<CaseStudy>(`/case-studies/${id}`)
    }
  }
  
  // 新闻资讯相关API
  static news = {
    /**
     * 获取新闻列表
     */
    getNews(params: PaginationParams & { category?: string; search?: string; featured?: boolean }) {
      return Request.get<PaginationResult<News>>('/news', params)
    },
    
    /**
     * 获取新闻详情
     */
    getNewsDetail(id: string) {
      return Request.get<News>(`/news/${id}`)
    },
    
    /**
     * 获取新闻分类
     */
    getNewsCategories() {
      return Request.getCached<NewsCategory[]>('/news/categories', undefined, {
        cache: true,
        cacheTTL: 10 * 60 * 1000
      })
    },
    
    /**
     * 获取热门新闻
     */
    getPopularNews(limit = 10) {
      return Request.getCached<News[]>('/news/popular', { limit }, {
        cache: true,
        cacheTTL: 5 * 60 * 1000
      })
    },
    
    /**
     * 获取相关新闻
     */
    getRelatedNews(newsId: string, limit = 5) {
      return Request.get<News[]>('/news/related', {
        newsId,
        limit
      })
    }
  }
  
  // 联系相关API
  static contact = {
    /**
     * 提交联系表单
     */
    submitForm(params: ContactForm) {
      const formData = new FormData()
      
      // 添加基本字段
      Object.keys(params).forEach(key => {
        if (key !== 'attachments') {
          formData.append(key, (params as any)[key])
        }
      })
      
      // 添加附件
      if (params.attachments) {
        params.attachments.forEach(file => {
          formData.append('attachments', file)
        })
      }
      
      return Request.post<ContactRecord>(
        '/contact/submit',
        formData,
        {
          headers: { 'Content-Type': 'multipart/form-data' },
          showSuccess: true,
          successMessage: '提交成功，我们会尽快与您联系'
        }
      )
    },
    
    /**
     * 获取联系记录
     */
    getRecords(params: PaginationParams & { status?: string; search?: string }) {
      return Request.get<PaginationResult<ContactRecord>>('/contact/records', params)
    },
    
    /**
     * 获取联系记录详情
     */
    getRecord(id: string) {
      return Request.get<ContactRecord>(`/contact/records/${id}`)
    }
  }
  
  // 文件上传相关API
  static upload = {
    /**
     * 上传单个文件
     */
    uploadFile(file: File, type?: string) {
      const formData = new FormData()
      formData.append('file', file)
      if (type) {
        formData.append('type', type)
      }
      
      return Request.upload<UploadResponse>('/upload/file', formData)
    },
    
    /**
     * 上传多个文件
     */
    uploadFiles(files: File[], type?: string) {
      const formData = new FormData()
      files.forEach(file => {
        formData.append('files', file)
      })
      if (type) {
        formData.append('type', type)
      }
      
      return Request.upload<UploadResponse[]>('/upload/files', formData)
    },
    
    /**
     * 上传图片
     */
    uploadImage(file: File) {
      return this.uploadFile(file, 'image')
    },
    
    /**
     * 上传文档
     */
    uploadDocument(file: File) {
      return this.uploadFile(file, 'document')
    }
  }
  
  // 统计相关API
  static statistics = {
    /**
     * 获取网站统计数据
     */
    getStatistics() {
      return Request.getCached<Statistics>('/statistics', undefined, {
        cache: true,
        cacheTTL: 5 * 60 * 1000
      })
    },
    
    /**
     * 记录页面访问
     */
    recordPageView(page: string, referrer?: string) {
      return Request.post('/statistics/page-view', {
        page,
        referrer,
        timestamp: Date.now()
      }, { showError: false })
    },
    
    /**
     * 记录事件
     */
    recordEvent(event: string, data?: any) {
      return Request.post('/statistics/event', {
        event,
        data,
        timestamp: Date.now()
      }, { showError: false })
    }
  }
  
  // 系统相关API
  static system = {
    /**
     * 获取系统配置
     */
    getConfig() {
      return Request.getCached<Record<string, any>>('/system/config', undefined, {
        cache: true,
        cacheTTL: 30 * 60 * 1000 // 30分钟缓存
      })
    },
    
    /**
     * 获取验证码
     */
    getCaptcha() {
      return Request.get<{ image: string; key: string }>('/system/captcha')
    },
    
    /**
     * 发送短信验证码
     */
    sendSmsCode(phone: string, type: 'register' | 'login' | 'reset') {
      return Request.post('/system/sms-code', {
        phone,
        type
      }, {
        showSuccess: true,
        successMessage: '验证码已发送'
      })
    },
    
    /**
     * 发送邮箱验证码
     */
    sendEmailCode(email: string, type: 'register' | 'login' | 'reset') {
      return Request.post('/system/email-code', {
        email,
        type
      }, {
        showSuccess: true,
        successMessage: '验证码已发送'
      })
    }
  }
}

// 导出API实例
export default API

// 导出类型
export type {
  LoginParams,
  RegisterParams,
  UserInfo,
  UpdateProfileParams,
  ChangePasswordParams,
  Product,
  ProductCategory,
  ProductFilter,
  ProductSort,
  Solution,
  CaseStudy,
  News,
  NewsCategory,
  ContactForm,
  ContactRecord,
  UploadResponse,
  Statistics
}